package com.wushi.lenovo.asia5b.app_ui.profile.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.mvp.base.BaseMvpActivity;
import com.mvp.base.model.ResultModel;
import com.mvp.helper.TimePickerHelper;
import com.mvp.helper.WCallBack;
import com.mvp.utils.InputMethodUtils;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.profile.mvpview.PersonalInfoActivityView;
import com.wushi.lenovo.asia5b.app_di.profile.presenter.PersonalInfoActivityPresenter;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.CancelSureDialog;
import com.wushi.lenovo.asia5b.app_utils.WTimeUtils;
import com.wushi.lenovo.asia5b.app_utils.WToastHelper;
import com.wushi.lenovo.asia5b.app_widget.ErrorTextView;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static java.lang.String.format;
import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2018/12/6.
 */
public class PersonalInfoActivity extends BaseMvpActivity<
        PersonalInfoActivityView, PersonalInfoActivityPresenter> implements PersonalInfoActivityView {
    @BindView(R.id.et_personal_name)
    EditText et_personal_name;
    @BindView(R.id.tv_personal_day)
    TextView tv_personal_day;
    @BindView(R.id.tv_personal_month)
    TextView tv_personal_month;
    @BindView(R.id.tv_personal_year)
    TextView tv_personal_year;
    @BindView(R.id.et_personal_email)
    TextView et_personal_email;
    @BindView(R.id.rb_personal_male)
    RadioButton rb_personal_male;
    @BindView(R.id.rb_personal_female)
    RadioButton rb_personal_female;
    @BindView(R.id.bt_personal_save)
    Button bt_personal_save;
    @BindView(R.id.bt_personal_cancle)
    Button bt_personal_cancle;
    @BindView(R.id.tv_personal_name_error)
    ErrorTextView tv_personal_name_error;
    @BindView(R.id.ll_personal_birthday)
    LinearLayout ll_personal_birthday;
    @BindView(R.id.tv_personal_birthday_error)
    TextView tv_personal_birthday_error;
    @BindView(R.id.rg_personal_vessel)
    RadioGroup rg_personal_vessel;

    private Date selectedDate;//text_yyyy_MM_dd
    private Date firstSelectedDate;//text_yyyy_MM_dd,初始的生日
    private String firstName;
    private boolean firstMaleIsChecked;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_personalinfo;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        setView();
    }

    private void setView() {


        UserInfo userInfo = UserInfo.getUserInfo();
        if (!TextUtils.isEmpty(userInfo.getBirthday())) {
            firstSelectedDate = WTimeUtils.getDate(userInfo.getBirthday(), WTimeUtils.format_dd_MM_yyyy);
            selectedDate = WTimeUtils.getDate(userInfo.getBirthday(), WTimeUtils.format_dd_MM_yyyy);
        }
        //name
        firstName = userInfo.getName();
        et_personal_name.setText(userInfo.getName());

        //birthday
        setBirthdayView();

        //email
        et_personal_email.setText(userInfo.getEmail());

        //gender
        rb_personal_male.setChecked(TextUtils.equals(userInfo.getGender(), "m"));
        rb_personal_female.setChecked(!TextUtils.equals(userInfo.getGender(), "m"));
        firstMaleIsChecked = rb_personal_male.isChecked();
    }

    @Override
    protected void initData() {

    }

    private void save() {
        boolean b = false;
        String name = et_personal_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            tv_personal_name_error.setVisibility(View.VISIBLE);
            b = true;
        }
        String birthday = "";
        if (selectedDate != null) {
            birthday = WTimeUtils.getDateFormatter(selectedDate, WTimeUtils.text_dd_MM_yyyy);
        }
        if (TextUtils.isEmpty(birthday)) {
            tv_personal_birthday_error.setVisibility(View.VISIBLE);
            b = true;
        }
        if (b) {
            return;
        }
        String gender = rb_personal_male.isChecked() ? "m" : "f";
        final Map<String, Object> map = MapHelper.newHashMap();
        map.put("member_id", UserInfo.getMemberId());
        map.put("name", name);
        map.put("birthday", birthday);
        map.put("gender", gender);
        map.put("country_id", UserInfo.getCountryId() + "");

        getPresenter().updateMember(map);

    }

    @Override
    protected void initEvent() {
        tv_personal_name_error.setBindEditText(et_personal_name);
    }


    private void setBirthdayView() {
        if (selectedDate == null) {
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(selectedDate);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);
        //day
        tv_personal_day.setText(day + "");

        //month
        String contentText = "";
        switch (month) {
            case 1:
                contentText = "January";
                break;
            case 2:
                contentText = "February";
                break;
            case 3:
                contentText = "March";
                break;
            case 4:
                contentText = "April";
                break;
            case 5:
                contentText = "May";
                break;
            case 6:
                contentText = "June";
                break;
            case 7:
                contentText = "July";
                break;
            case 8:
                contentText = "August";
                break;
            case 9:
                contentText = "September";
                break;
            case 10:
                contentText = "October";
                break;
            case 11:
                contentText = "November";
                break;
            case 12:
                contentText = "December";
                break;
        }
        tv_personal_month.setText(contentText);

        //year
        tv_personal_year.setText(year + "");
    }


    @OnClick({
            R.id.bt_personal_save,
            R.id.bt_personal_cancle,
            R.id.ll_personal_birthday
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_personal_save:
                save();
                break;
            case R.id.bt_personal_cancle:
                finish();
                break;
            case R.id.ll_personal_birthday:
                InputMethodUtils.closeKeyBoard(this);
                String selectedDateText;
                if (selectedDate == null) {
                    selectedDateText = WTimeUtils.getDateFormatter(new Date(), WTimeUtils.text_yyyy_MM_dd);
                } else {
                    selectedDateText = WTimeUtils.getDateFormatter(selectedDate, WTimeUtils.text_yyyy_MM_dd);
                }

                TimePickerHelper.getInstance().getTimePickerDialog(this
                        , null, null, null, selectedDateText, null, new OnTimeSelectListener() {
                            @Override
                            public void onTimeSelect(Date date, View v) {
                                selectedDate = date;
                                setBirthdayView();
                                tv_personal_birthday_error.setVisibility(View.GONE);
                            }
                        }).show();
                break;
            default:
                break;
        }

    }


    /**
     * 监听返回键，如果左侧栏在打开状态就先去关闭，否则双击两次直接退出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isChanged()) {
            finishNotice();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean isChanged() {
        try {
            String name = et_personal_name.getText().toString().trim();
            d("--->>>>>>>>---" + format("初始姓名:%s,修改后姓名:%s", firstName, name));
            if (!TextUtils.equals(name, firstName)) {
                return true;
            }
            if (firstSelectedDate == null && selectedDate != null) {
                d(format("--->>>>>>>>---初始没有生日,选择生日:%s", selectedDate.getTime() + ""));
                return true;
            } else if (firstSelectedDate != null && selectedDate == null) {
                d(format("--->>>>>>>>---初始生日:%s,没有选择生日", firstSelectedDate.getTime() + ""));
            } else {
                if (selectedDate != null && firstSelectedDate != null) {
                    if (selectedDate.getTime() != firstSelectedDate.getTime()) {
                        d("--->>>>>>>>---" + format("初始生日:%s,修改后姓名:%s", firstSelectedDate.getTime() + "", selectedDate.getTime() + ""));
                        return true;
                    }
                }
            }
            d("--->>>>>>>>---" + format("初始性别:%s,修改后性别:%s", rb_personal_male.isChecked() + "", firstMaleIsChecked + ""));
            if (!(rb_personal_male.isChecked() == firstMaleIsChecked)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public void backClick(View v) {
        if (isChanged()) {
            finishNotice();
        } else {
            super.backClick(v);
        }
    }

    private void finishNotice() {
        new CancelSureDialog(this, R.string.yes, R.string.no
                , R.string.personalinfo_finish_notice, new WCallBack() {
            @Override
            public void callback(Object o) {
                finish();
            }
        }).show();
    }


    @Override
    public void updateMemberResult(ResultModel resultModel, Map<String, Object> map) {
        if (resultModel.isSuccess()) {
            WToastHelper.showContentView(this, R.string.personalinfo_update_success);
            UserRepository.updateUserInfo();
            finish();
        }
    }
}
